package com.zjitc.service.imp;

import com.zjitc.common.Gsonal;
import com.zjitc.common.ServerResponse;
import com.zjitc.common.redis.RedisCache;
import com.zjitc.mapper.*;
import com.zjitc.pojo.Category;
import com.zjitc.service.CategoryService;
import com.zjitc.utils.old.RedisAuto;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Create By IntelliJ IDEA
 *
 * @author: myq
 * @create-Time: 2017/11/14  16:03
 */
@Service
public class CategoryServiceImpl implements CategoryService {
    @Autowired
    private CategoryMapper dao;

    @Autowired
    private RedisCache redis;

    private final String CATEGORYS = "categorys";

    private static final Logger log = Logger.getLogger(CarServiceImpl.class);

    @Override
    public ServerResponse<Category> findAll() {
        checkcategory();
        List<Category> categories = redis.hashListGetAll(CATEGORYS, Category.class);
        return ServerResponse.createSuccess(categories);
    }


    @Override
    public List<Category> adminfindAll() {
        checkcategory();
        return redis.hashListGetAll(CATEGORYS, Category.class);
    }

    @Override
    public boolean update(Category category) {
        redis.hashset(CATEGORYS, category.getCid(), Gsonal.tojson(category));
        return dao.update(category) == 1;
    }

    @Override
    public boolean deletebycid(String cid) {
        try {
            int i = dao.deletebycid(cid);
            redis.delHash(CATEGORYS, cid);
            return i == 1;
        }catch (Exception e){
            return false;
        }
    }

    @Override
    public Category findByCid(String cid) {
        return findbycid(cid);
    }

    @Override
    public boolean add(Category category) {
        int i = dao.add(category);
        redis.hashset(CATEGORYS,category.getCid(),Gsonal.tojson(category));
        return i == 1;
    }

    private void checkcategory() {
        if (!redis.exists(CATEGORYS)) {
            RedisAuto.categoryRedis(dao, redis, CATEGORYS);
        }
    }

    private Category findbycid(String cid){
        return redis.hashgetObject(CATEGORYS, cid, Category.class);
    }
}
